package com.dy.yunying.biz.service.hongbao.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dy.yunying.api.dto.hongbao.HbReceivingRecordDto;
import com.dy.yunying.api.entity.ParentGameDO;
import com.dy.yunying.api.entity.WanGameDO;
import com.dy.yunying.api.entity.hongbao.HbActivity;
import com.dy.yunying.api.entity.hongbao.HbReceivingAddress;
import com.dy.yunying.api.entity.hongbao.HbReceivingRecord;
import com.dy.yunying.api.enums.ActivityEventEnum;
import com.dy.yunying.api.req.ParentGameReq;
import com.dy.yunying.api.vo.hongbao.HbReceivingRecordVo;
import com.dy.yunying.biz.config.YunYingProperties;
import com.dy.yunying.biz.dao.ads.hongbao.HbActivityMapper;
import com.dy.yunying.biz.dao.ads.hongbao.HbReceivingRecordMapper;
import com.dy.yunying.biz.service.hongbao.HbActivityRoleInfoService;
import com.dy.yunying.biz.service.hongbao.HbReceivingAddressService;
import com.dy.yunying.biz.service.hongbao.HbReceivingRecordService;
import com.dy.yunying.biz.service.manage.GameService;
import com.dy.yunying.biz.service.manage.ParentGameService;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 奖品领取记录
 *
 * @author chenxiang
 * @version 2021-10-25 14:21:04
 * table: hb_receiving_record
 */
@Log4j2
@Service("hbReceivingRecordService")
@RequiredArgsConstructor
public class HbReceivingRecordServiceImpl extends ServiceImpl<HbReceivingRecordMapper, HbReceivingRecord> implements HbReceivingRecordService {

	private static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd HH:mm:ss.SSS").toFormatter();

	private final YunYingProperties properties;

	private final HbReceivingRecordMapper hbReceivingRecordMapper;

	private final HbReceivingAddressService hbReceivingAddressService;

	private final HbActivityMapper hbActivityMapper;

	private final ParentGameService parentGameService;

	private final GameService gameService;

	private final KafkaTemplate<String, Object> kafkaTemplate;

	/**
	 * 领取记录列表 - page
	 *
	 * @param vo
	 * @return
	 */
	@Override
	public R getPage(HbReceivingRecordVo vo) {
		IPage<HbReceivingRecordDto> iPage = hbReceivingRecordMapper.selectRecordByPage(vo);
		// 处理数据
		dealData(iPage);
		return R.ok(iPage);
	}

	/**
	 * 导出
	 *
	 * @param vo
	 * @return
	 */
	@Override
	public List<HbReceivingRecordDto> exportRecord(HbReceivingRecordVo vo) {
		vo.setCurrent(1);
		vo.setSize(999999);
		vo.setObjectType("1");
		vo.setType("3");
		IPage<HbReceivingRecordDto> iPage = hbReceivingRecordMapper.selectRecordByPage(vo);
		// 处理数据
		dealData(iPage);
		List<HbReceivingRecordDto> list = iPage.getRecords();
		return list;
	}

	/**
	 * 审核礼品
	 *
	 * @param vo
	 * @return
	 */
	@Override
	@Transactional(value = "adsTransactionManager", rollbackFor = Exception.class)
	public R verifyRecord(HbReceivingRecordVo vo) {
		try {
			//根据ID获取基本信息
			HbReceivingRecord receivingRecord = new HbReceivingRecord();
			receivingRecord.setId(Long.valueOf(vo.getId()));
			receivingRecord.setStatus(Integer.valueOf(vo.getStatus()));
			receivingRecord.setForbidReason(vo.getForbidReason());
			receivingRecord.setUpdateId(Long.valueOf(SecurityUtils.getUser().getId()));
			receivingRecord.setUpdateTime(new Date());
			boolean flag = this.updateById(receivingRecord);
			if (flag) {
				// object_type = 2 表示 提现的是游戏货币(实质是领取了一个礼包码)
				HbReceivingRecord record = this.getById(vo.getId());
				final HbActivity activity = hbActivityMapper.selectById(record.getActivityId());
				final LocalDateTime now = LocalDateTime.now();
				String recordValue = new JSONObject()
						.fluentPut("eventType", ActivityEventEnum.INKIND_GIFTS_REJECTED.getCode())
						.fluentPut("eventTime", DATE_TIME_FORMATTER.format(now))
						.fluentPut("userId", record.getUserId())
						.fluentPut("username", record.getUserName())
						.fluentPut("parentChl", record.getParentChl())
						.fluentPut("chl", record.getChl())
						.fluentPut("appChl", record.getAppChl())
						.fluentPut("pGameId", record.getParentGameId())
						.fluentPut("gameId", record.getGameId())
						.fluentPut("areaId", record.getAreaId())
						.fluentPut("roleId", record.getRoleId())
						.fluentPut("roleName", record.getRoleName())
						.fluentPut("activityId", record.getActivityId())
						.fluentPut("activityName", activity.getActivityName())
						.fluentPut("activityType", activity.getActivityType())
						.fluentPut("dynamicTypeId", activity.getDynamicTypeId())
						.fluentPut("redpackId", record.getObjectId())
						.fluentPut("receiveId", vo.getId())
						.toJSONString();
				log.info("发送kafka信息，实物订单驳回申请{}", recordValue);
				kafkaTemplate.send(properties.getActivityEventTopic(), String.valueOf(record.getUserId()), recordValue.getBytes(StandardCharsets.UTF_8));
				return R.ok();
			}
		} catch (Exception e) {
			log.error("审核礼品异常：", e);
			throw new RuntimeException(e);
		}
		return R.failed();
	}

	/**
	 * 发货 - 填写快递信息
	 *
	 * @param vo
	 * @return
	 */
	@Override
	@Transactional(value = "adsTransactionManager", rollbackFor = Exception.class)
	public R deliverGoods(HbReceivingRecordVo vo) {
		try {
			HbReceivingRecord receivingRecord = new HbReceivingRecord();
			receivingRecord.setId(Long.valueOf(vo.getId()));
			receivingRecord.setStatus(5);
			receivingRecord.setUpdateId(Long.valueOf(SecurityUtils.getUser().getId()));
			receivingRecord.setUpdateTime(new Date());
			this.updateById(receivingRecord);

			QueryWrapper<HbReceivingAddress> wrapper = new QueryWrapper<>();
			wrapper.eq("record_id", vo.getId());
			wrapper.eq("deleted", 0);
			HbReceivingAddress receivingAddress = new HbReceivingAddress();
			receivingAddress.setSendTime(new Date());
			receivingAddress.setExpressName(vo.getExpressName());
			receivingAddress.setExpressCode(vo.getExpressCode());
			receivingAddress.setUpdateId(Long.valueOf(SecurityUtils.getUser().getId()));
			receivingAddress.setUpdateTime(new Date());
			boolean updateBool = hbReceivingAddressService.update(receivingAddress, wrapper);
			if (updateBool) {
				//根据ID获取基本信息
				// object_type = 2 表示 提现的是游戏货币(实质是领取了一个礼包码)
				HbReceivingRecord record = this.getById(vo.getId());
				final HbActivity activity = hbActivityMapper.selectById(record.getActivityId());
				final LocalDateTime now = LocalDateTime.now();
				String recordValue = new JSONObject()
						.fluentPut("eventType", ActivityEventEnum.INKIND_GIFTS_SHIPPED.getCode())
						.fluentPut("eventTime", DATE_TIME_FORMATTER.format(now))
						.fluentPut("userId", record.getUserId())
						.fluentPut("username", record.getUserName())
						.fluentPut("parentChl", record.getParentChl())
						.fluentPut("chl", record.getChl())
						.fluentPut("appChl", record.getAppChl())
						.fluentPut("pGameId", record.getParentGameId())
						.fluentPut("gameId", record.getGameId())
						.fluentPut("areaId", record.getAreaId())
						.fluentPut("roleId", record.getRoleId())
						.fluentPut("roleName", record.getRoleName())
						.fluentPut("activityId", record.getActivityId())
						.fluentPut("activityName", activity.getActivityName())
						.fluentPut("activityType", activity.getActivityType())
						.fluentPut("dynamicTypeId", activity.getDynamicTypeId())
						.fluentPut("redpackId", record.getObjectId())
						.fluentPut("receiveId", vo.getId())
						.toJSONString();
				log.info("发送kafka信息,实物订单发货{}", recordValue);
				kafkaTemplate.send(properties.getActivityEventTopic(), String.valueOf(record.getUserId()), recordValue.getBytes(StandardCharsets.UTF_8));
			}
			return R.ok();
		} catch (Exception e) {
			log.error("礼品发货异常：", e);
			throw new RuntimeException();
		}
	}

	/**
	 * 处理列表数据
	 *
	 * @param iPage
	 */
	public void dealData(IPage<HbReceivingRecordDto> iPage) {
		try {
			if (Objects.nonNull(iPage) && Objects.nonNull(iPage.getRecords())) {
				List<HbReceivingRecordDto> list = iPage.getRecords();
				// 获取父游戏列表
				Collection<Long> parentGameIds = list.stream().map(item -> {
					return Long.valueOf(String.valueOf(item.getParentGameId()));
				}).collect(Collectors.toSet());
				List<ParentGameDO> parentGameList = parentGameService.getCacheablePGameList(new ParentGameReq().setIds(parentGameIds));
				// 获取子游戏列表
				Collection<Long> gameIds = list.stream().map(item -> {
					return Long.valueOf(String.valueOf(item.getGameId()));
				}).collect(Collectors.toSet());
				gameIds.add(0L);
				List<WanGameDO> gameList = gameService.list(Wrappers.<WanGameDO>query().lambda().in(WanGameDO::getId, gameIds));

				for (HbReceivingRecordDto receivingRecordDto : list) {
					// 获取父游戏名称
					if (Objects.nonNull(parentGameList) && parentGameList.size() > 0) {
						parentGameList.forEach(game -> {
							if (receivingRecordDto.getParentGameId().intValue() == game.getId().intValue()) {
								receivingRecordDto.setParentGameName(game.getGname());
							}
						});
					}
					// 获取子游戏名称
					if (Objects.nonNull(gameList) && gameList.size() > 0) {
						gameList.forEach(game -> {
							if (receivingRecordDto.getGameId().intValue() == game.getId().intValue()) {
								receivingRecordDto.setGameName(game.getGname());
							}
						});
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


